<template>
  <div class="customer-list-container">
    <el-card class="role-card">
      <template #header>
        <div class="card-header">
          <span>客户管理</span>
          <div class="header-buttons">
            <el-button type="primary" @click="handleAdd">新增客户</el-button>
          </div>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form :model="queryForm" inline class="query-form">
        <el-form-item label="客户名称">
          <el-input v-model="queryForm.name" placeholder="请输入客户名称" clearable />
        </el-form-item>
        <el-form-item label="客户阶段">
          <el-select v-model="queryForm.stage" placeholder="请选择客户阶段" clearable>
            <el-option
              v-for="stage in customerStages"
              :key="stage.value"
              :label="stage.label"
              :value="stage.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户来源">
          <el-select v-model="queryForm.source" placeholder="请选择客户来源" clearable>
            <el-option
              v-for="source in customerSources"
              :key="source.value"
              :label="source.label"
              :value="source.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="queryForm.status" placeholder="请选择审核状态" clearable>
            <el-option label="待审核" value="PENDING" />
            <el-option label="已通过" value="APPROVED" />
            <el-option label="已拒绝" value="INACTIVE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchCustomers">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 客户列表 -->
      <el-table
        :data="customers"
        v-loading="loading"
        stripe
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column
          prop="name"
          label="客户名称"
          min-width="150"
          show-overflow-tooltip
          align="left"
        />
        <el-table-column prop="stage" label="客户阶段" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStageType(row.stage)" size="small" effect="light">
              {{ getStageName(row.stage) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="客户来源" width="120" align="center">
          <template #default="{ row }">
            <span class="table-cell-text">{{ getSourceName(row.source) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contactName" label="联系人" width="120" align="center">
          <template #default="{ row }">
            <span class="table-cell-text">{{ row.contactName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="contactPhone" label="联系电话" width="120" align="center">
          <template #default="{ row }">
            <span class="table-cell-text">{{ row.contactPhone }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="visitAddress"
          label="拜访地址"
          min-width="200"
          show-overflow-tooltip
          align="left"
        >
          <template #default="{ row }">
            <span class="table-cell-text">{{ row.visitAddress }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="审核状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small" effect="light">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right" align="center">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button type="primary" link @click="handleView(row)">查看</el-button>
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="success" link @click="handleDepartment(row)">部门</el-button>
              <el-button
                v-if="row.status === 'PENDING'"
                type="warning"
                link
                @click="handleApprove(row)"
              >
                审核
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 客户表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="客户阶段" prop="stage">
          <el-select v-model="form.stage" placeholder="请选择客户阶段">
            <el-option
              v-for="stage in customerStages"
              :key="stage.value"
              :label="stage.label"
              :value="stage.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户来源" prop="source">
          <el-select v-model="form.source" placeholder="请选择客户来源">
            <el-option
              v-for="source in customerSources"
              :key="source.value"
              :label="source.label"
              :value="source.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="拜访地址" prop="visitAddress">
          <el-input
            v-model="form.visitAddress"
            type="textarea"
            :rows="3"
            placeholder="请输入拜访地址"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 部门关联对话框 -->
    <DepartmentDialog
      v-if="departmentForm.customerId"
      v-model:visible="departmentDialogVisible"
      :customer-id="departmentForm.customerId"
      @update:visible="
        (val) => {
          departmentDialogVisible = val
          if (!val) {
            departmentForm.customerId = undefined
          }
        }
      "
    />

    <!-- 审核对话框 -->
    <el-dialog
      title="客户审核"
      v-model="approveDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="approveFormRef" :model="approveForm" :rules="approveRules" label-width="100px">
        <el-form-item label="审核结果" prop="approved">
          <el-radio-group v-model="approveForm.approved">
            <el-radio :label="true">通过</el-radio>
            <el-radio :label="false">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="comment">
          <el-input
            v-model="approveForm.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleApproveSubmit" :loading="approveSubmitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getCustomers,
  createCustomer,
  updateCustomer,
  deleteCustomer,
  approveCustomer,
  getCustomerDepartments,
  addCustomerDepartment,
  deleteCustomerDepartment,
  getAllDepartments,
  getAllSales,
} from '@/api/customer'
import type { Customer, CustomerQuery } from '@/types/customer'
import type { PageResponse } from '@/types/common'
import type { CustomerDepartment, Department, Sales } from '@/api/customer'
import DepartmentDialog from './DepartmentDialog.vue'
import axios from 'axios'

const router = useRouter()

const loading = ref(false)
const submitting = ref(false)
const customers = ref<Customer[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框状态
const dialogVisible = ref(false)
const departmentDialogVisible = ref(false)
const approveDialogVisible = ref(false)
const dialogTitle = ref('')

// 表单引用
const formRef = ref()
const approveFormRef = ref()

// 查询表单
const queryForm = reactive<CustomerQuery>({
  name: '',
  stage: '',
  source: '',
  status: '',
})

// 客户表单
const form = reactive<Partial<Customer>>({
  id: undefined,
  name: '',
  stage: '',
  source: '',
  contactName: '',
  contactPhone: '',
  visitAddress: '',
})

// 审核表单
const approveForm = reactive({
  id: undefined as number | undefined,
  approved: true,
  comment: '',
})

// 部门表单
const departmentForm = reactive({
  customerId: undefined as number | undefined,
  departmentId: undefined as number | undefined,
  salesId: undefined as number | undefined,
})

// 部门相关状态
const customerDepartments = ref<CustomerDepartment[]>([])
const departments = ref<Department[]>([])
const salesList = ref<Sales[]>([])
const approveSubmitting = ref(false)
const departmentLoading = ref(false)
const salesLoading = ref(false)
const departmentSubmitting = ref(false)

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
  stage: [{ required: true, message: '请选择客户阶段', trigger: 'change' }],
  source: [{ required: true, message: '请选择客户来源', trigger: 'change' }],
  contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
  contactPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
}

const approveRules = {
  approved: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
  comment: [{ required: true, message: '请输入审核意见', trigger: 'blur' }],
}

// 客户阶段选项
const customerStages = [
  { value: 'LEAD', label: '潜在客户' },
  { value: 'QUALIFIED', label: '已确认需求' },
  { value: 'PROPOSAL', label: '方案报价' },
  { value: 'NEGOTIATION', label: '商务谈判' },
  { value: 'CONTRACT', label: '合同签订' },
  { value: 'IMPLEMENTATION', label: '实施交付' },
  { value: 'MAINTENANCE', label: '售后维护' },
  { value: 'LOST', label: '已流失' },
]

// 客户来源选项
const customerSources = [
  { value: 'TELEMARKETING', label: '电话营销' },
  { value: 'WEBSITE', label: '官网' },
  { value: 'SOCIAL_MEDIA', label: '社交媒体' },
  { value: 'REFERRAL', label: '客户推荐' },
  { value: 'EXHIBITION', label: '展会' },
  { value: 'SEARCH_ENGINE', label: '搜索引擎' },
  { value: 'EMAIL_MARKETING', label: '邮件营销' },
  { value: 'PARTNER', label: '合作伙伴' },
  { value: 'OTHER', label: '其他' },
]

// 获取客户列表
const fetchCustomers = async () => {
  loading.value = true
  try {
    const response = await getCustomers({
      page: currentPage.value - 1,
      size: pageSize.value,
      ...queryForm,
    })
    console.log('加载的客户数据:', response)
    const data = response.data as PageResponse<Customer>
    customers.value = data.content
    total.value = data.totalElements
  } catch (error) {
    console.error('加载客户列表失败:', error)
    ElMessage.error('加载客户列表失败')
  } finally {
    loading.value = false
  }
}

// 重置查询
const resetQuery = () => {
  queryForm.name = undefined
  queryForm.stage = undefined
  queryForm.source = undefined
  queryForm.status = undefined
  fetchCustomers()
}

// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchCustomers()
}

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchCustomers()
}

// 新增客户
const handleAdd = () => {
  router.push('/customers/create')
}

// 查看客户详情
const handleView = (row: Customer) => {
  router.push(`/customers/${row.id}`)
}

// 编辑客户
const handleEdit = (row: Customer) => {
  router.push(`/customers/${row.id}/edit`)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: unknown) => {
    if (typeof valid !== 'boolean') return
    if (valid && form.id !== undefined) {
      submitting.value = true
      try {
        if (form.id) {
          await updateCustomer(form.id, form)
          ElMessage.success('更新客户成功')
        } else {
          await createCustomer(form)
          ElMessage.success('创建客户成功')
        }
        dialogVisible.value = false
        fetchCustomers()
      } catch (error) {
        ElMessage.error(form.id ? '更新客户失败' : '创建客户失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 删除客户
const handleDelete = async (row: Customer) => {
  try {
    await ElMessageBox.confirm('确认删除该客户吗？', '提示', {
      type: 'warning',
    })
    await deleteCustomer(row.id!)
    // 记录删除日志
    await axios.post('/api/logs', {
      action: 'DELETE_CUSTOMER',
      description: `删除客户：${row.name}`,
    })
    ElMessage.success('删除成功')
    fetchCustomers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除客户失败:', error)
      ElMessage.error('删除客户失败')
    }
  }
}

// 打开部门关联对话框
const handleDepartment = async (row: Customer) => {
  console.log('打开部门对话框，客户ID:', row.id)
  departmentForm.customerId = row.id
  departmentDialogVisible.value = true
}

// 获取客户关联的部门
const fetchCustomerDepartments = async (customerId: number) => {
  try {
    const response = await getCustomerDepartments(customerId)
    customerDepartments.value = response.data
  } catch (error) {
    ElMessage.error('获取客户部门失败')
  }
}

// 搜索部门
const searchDepartments = async (query: string) => {
  if (query) {
    departmentLoading.value = true
    try {
      const response = await getAllDepartments()
      // 在前端进行过滤
      departments.value = response.data.filter((dept) =>
        dept.name.toLowerCase().includes(query.toLowerCase()),
      )
    } catch (error) {
      ElMessage.error('搜索部门失败')
    } finally {
      departmentLoading.value = false
    }
  } else {
    // 如果没有搜索词，显示所有部门
    try {
      const response = await getAllDepartments()
      departments.value = response.data
    } catch (error) {
      ElMessage.error('加载部门列表失败')
    }
  }
}

// 搜索销售
const searchSales = async (query: string) => {
  if (query) {
    salesLoading.value = true
    try {
      const response = await getAllSales(query)
      salesList.value = response.data
    } catch (error) {
      ElMessage.error('搜索销售失败')
    } finally {
      salesLoading.value = false
    }
  } else {
    salesList.value = []
  }
}

// 添加部门关联
const handleAddDepartment = async () => {
  if (!departmentForm.departmentId || !departmentForm.salesId || !departmentForm.customerId) {
    ElMessage.warning('请选择部门和销售负责人')
    return
  }

  departmentSubmitting.value = true
  try {
    await addCustomerDepartment({
      customerId: departmentForm.customerId,
      departmentId: departmentForm.departmentId,
      salesId: departmentForm.salesId,
    })
    ElMessage.success('添加部门成功')
    await fetchCustomerDepartments(departmentForm.customerId)
    // 重置表单
    departmentForm.departmentId = undefined
    departmentForm.salesId = undefined
  } catch (error) {
    ElMessage.error('添加部门失败')
  } finally {
    departmentSubmitting.value = false
  }
}

// 删除部门关联
const handleDeleteDepartment = async (departmentId: number) => {
  if (!departmentForm.customerId) {
    ElMessage.error('客户ID不能为空')
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除该部门关联吗？', '提示', {
      type: 'warning',
    })

    await deleteCustomerDepartment(departmentForm.customerId, departmentId)
    ElMessage.success('删除部门成功')
    await fetchCustomerDepartments(departmentForm.customerId)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除部门失败')
    }
  }
}

// 打开审核对话框
const handleApprove = (row: Customer) => {
  approveForm.id = row.id
  approveForm.approved = true
  approveForm.comment = ''
  approveDialogVisible.value = true
}

// 提交审核
const handleApproveSubmit = async () => {
  if (!approveFormRef.value) return

  await approveFormRef.value.validate(async (valid: unknown) => {
    if (typeof valid !== 'boolean') return
    if (valid) {
      try {
        if (approveForm.id === undefined) return
        await approveCustomer(approveForm.id, {
          approved: approveForm.approved,
          comment: approveForm.comment,
        })
        ElMessage.success('审核成功')
        approveDialogVisible.value = false
        fetchCustomers()
      } catch (error) {
        ElMessage.error('审核失败')
      }
    }
  })
}

// 获取客户阶段标签样式
const getStageType = (stage: string) => {
  const types = {
    LEAD: 'info',
    QUALIFIED: 'success',
    PROPOSAL: 'warning',
    NEGOTIATION: 'warning',
    CONTRACT: 'success',
    IMPLEMENTATION: 'primary',
    MAINTENANCE: 'success',
    LOST: 'danger',
  }
  return (types as Record<string, string>)[stage] || 'info'
}

// 获取客户阶段显示名称
const getStageName = (stage: string) => {
  const stageObj = customerStages.find((s) => s.value === stage)
  return stageObj ? stageObj.label : stage
}

// 获取客户来源显示名称
const getSourceName = (source: string) => {
  const sourceObj = customerSources.find((s) => s.value === source)
  return sourceObj ? sourceObj.label : source
}

// 获取审核状态标签样式
const getStatusType = (status: string) => {
  const types = {
    PENDING: 'warning',
    APPROVED: 'success',
    INACTIVE: 'danger',
  }
  return (types as Record<string, string>)[status] || 'info'
}

// 获取审核状态显示名称
const getStatusName = (status: string) => {
  const names = {
    PENDING: '待审核',
    APPROVED: '已通过',
    INACTIVE: '已拒绝',
  }
  return (names as Record<string, string>)[status] || status
}

// 记录页面访问日志
const recordPageAccess = async () => {
  try {
    await axios.post('/api/logs', {
      action: 'ACCESS_PAGE',
      description: '访问客户管理页面',
    })
  } catch (error) {
    console.error('记录页面访问日志失败:', error)
  }
}

// 初始化
onMounted(() => {
  fetchCustomers()
  recordPageAccess()
})
</script>

<style scoped>
.role-container {
  padding: 20px;
}

.role-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.query-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-table {
  margin: 0 20px;
}

.el-table :deep(th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  height: 50px;
  padding: 8px 0;
}

.el-table :deep(td) {
  padding: 12px 0;
  height: 50px;
}

.el-table :deep(.cell) {
  line-height: 1.5;
  white-space: nowrap;
  padding: 0 12px;
}

.table-cell-text {
  color: #606266;
  font-size: 14px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.el-table :deep(.el-button--link) {
  padding: 4px 8px;
  font-size: 14px;
}

.el-table :deep(.el-tag) {
  border-radius: 2px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

.el-table :deep(.el-tag--light) {
  border-width: 1px;
}

.department-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.department-list {
  margin-bottom: 20px;
}

.department-add {
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
}

.department-list h3,
.department-add h3 {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.table-cell-text {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}
</style>
